package com.frame.framework.config;

import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.frame.common.utils.spring.SpringUtils;
import com.frame.framework.aspectj.lang.enums.DataSourceType;
import com.frame.framework.datasource.DynamicDataSource;

/**
 * 
 * @className ：DruidPrimaryConfig
 * @describe ：数据源设置
 */
@Configuration
public class DruidPrimaryConfig {

	@Bean(name = "dynamicDataSource")
    public DynamicDataSource dataSource(DataSource masterDataSource){
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceType.MASTER.name(), masterDataSource);
        setDataSource(targetDataSources, DataSourceType.SLAVE.name(), "slaveDataSource");
        return new DynamicDataSource(masterDataSource, targetDataSources);
    }
   	
   	 /**
        * 设置数据源
        * 
        * @param targetDataSources 备选数据源集合
        * @param sourceName 数据源名称
        * @param beanName bean名称
        */
    public void setDataSource(Map<Object, Object> targetDataSources, String sourceName, String beanName){
       try{
           DataSource dataSource = SpringUtils.getBean(beanName);
           targetDataSources.put(sourceName, dataSource);
       }catch (Exception e){
       }
    }
}
